import fetch from './fetch';

const __call = (uri, params, postbody, options = {}) => {
  const { callback, dispatch, actionType, errorHandler, ...otherOptions } = options;

  return fetch(uri, params, postbody, { ...otherOptions }).then((res) => {
    callback && callback(res);
    actionType && dispatch && dispatch({
      type: actionType,
      payload: res
    });
    return res;
  }).catch((error) => {
    console.log('fetch error:', error);
    return error
  });
};

const __station = (api, params, options = {}) => {
  const { mock, request, ...reqOptions } = options;
  const uri = mock || api;

  return __call(uri, params, request, reqOptions);
};

export default {
  get: (uri, params, options = {}) => {
    const getOptions = Object.assign({ cache: true }, options, { type: 'GET' });
    return __station(uri, params, getOptions);
  }
};
